<?php
namespace Home\Controller;
use Think\Controller;
use App\Controller\BaseController;
class OrderController extends BaseController {

    public function _initialize(){
        //如果session存在，传递用户信息
        $midiuser = session('midiuser');
        if(empty($midiuser)){
            $this->redirect('Home/Index/login');
        }
        $this->assign('midiuser',$midiuser);
    }

    /**
     * 订单相关操作
     *
    */
    //确认订单
    public function sureOrder()
    {
        //如果session存在，传递用户信息
        $midiuser = session('midiuser');
        if (!empty($midiuser)) {
            $this->assign('midiuser',$midiuser);
        }else{
            $this->error('您尚未登录，请去登录',U('Home/Index/login'));
        }
        //需要购买的商品   ID:NUM,ID:NUM
        $order_id = I('order_id',0,'intval');
        if($order_id > 0){
            //待付款订单再次付款
            $order_info = M('order')
                ->field('order_id,order_name,order_num,order_details,order_totalprice')
                ->where(['order_id'=>$order_id,'order_user_id'=>$midiuser['user_id'],'order_paystatus'=>1])
                ->find();
            if(empty($order_info)){
                $this->error('参数有误！',U('Home/Order/orderList'));
            }else{
                $idStr = setGoodsDetailData($order_info['order_details']);
                $toType = 1;
            }
        }else{
            $idStr = I('idStr');
            $toType = I('toType',2,'intval'); //1立即支付方式，2从购物车中
            if(!empty($idStr)){
                //处理数据并验证数据
                $idStr = setGoodsDetailData($idStr);
                $check = true;
                foreach ($idStr['data'] as $val) {
                    if($val['goods_id'] <= 0 || $val['goods_num'] <= 0){
                        $check = false;
                        break;
                    }
                }
                if(!$check){
                    $this->error('参数异常！',U('GoodsCart/cart_list'));
                    return;
                }
                $_SESSION['sure_goods_data'] = ['idStr'=>$idStr,'toType'=>$toType];
            }else{
                $sure_goods_data = $_SESSION['sure_goods_data'];
                $idStr = $sure_goods_data['idStr'];
                $toType = $sure_goods_data['toType'];
            }
        }
        if(empty($idStr) || empty($toType)){
            $this->error('请选择需要购买的商品！',U('GoodsCart/cart_list'));
        }
//        var_dump($idStr);
        //查询所有商品
        $sure_goods = M('goods')
            ->field('goods_id,goods_name,goods_price,goods_pic')
            ->where([
                'goods_id'=>['in',$idStr['goods_id_arr']],
                'goods_sell_out'=>1,
                'goods_display'=>1,
            ])
            ->select();
//        var_dump($sure_goods);
        //组合数据
        $total_prices = 0;
        $sure_id_str = '';
        if(!empty($sure_goods)){
            foreach ($sure_goods as $key => $val) {
                foreach ($idStr['data'] as $k => $v) {
                    if($val['goods_id'] == $v['goods_id']){
                        $sure_goods[$key]['goods_num'] = $v['goods_num'];
                        $sure_goods[$key]['prices'] = $val['goods_price'] * $v['goods_num'];
                        $total_prices += $sure_goods[$key]['prices'];
                        $sure_id_str .= $val['goods_id'].':'.$v['goods_num'].',';
                        unset($idStr['data'][$k]);
                        continue;
                    }
                }
            }
        }
//        var_dump($sure_goods);
        //所有收货地址
        $address_list = M('address')
            ->field('address_display',true)
            ->where(['address_user_id'=>$midiuser['user_id'],'address_display'=>1])
            ->select();
        //默认收货地址为
        $order_address = 0;
        if(!empty($address_list)){
            foreach ($address_list as $value) {
                if($value['address_default'] == 1){
                    $order_address = $value['address_id'];
                }
            }
        }
        $this->assign('toType',$toType);
        $this->assign('address_list',$address_list);
        $this->assign('sure_goods',$sure_goods);
        $this->assign('total_prices',$total_prices);
        $this->assign('sure_id_str',trim($sure_id_str,','));
        $this->assign('order_address',$order_address);
        $this->assign('order_id',$order_id);
        $this->display();
    }
    //确认订单中添加收货地址
    public function addAddress()
    {
        //如果session存在，传递用户信息
        $midiuser = session('midiuser');
        if (!empty($midiuser)) {
            $this->assign('midiuser',$midiuser);
        }else{
            $this->error('您尚未登录，请去登录',U('Home/Index/login'));
        }
        if(IS_POST){
            $data = I('post.');
            if(empty($data['address_username']) ||
                empty($data['province3']) ||
                empty($data['city3']) ||
                empty($data['address_detail']) ||
                empty($data['address_zipcode']) ||
                empty($data['address_userphone'])
            ){
                $this->error('信息不全！','sureOrder');
            }
            if(!isMobile($data['address_userphone'])){
                $this->error('手机号格式不正确！','sureOrder');
            }
            $data['address_address'] = $data['province3'].$data['city3'].$data['area3'].$data['address_detail'];
//            var_dump($data);
            $data['address_user_id'] = $midiuser['user_id'];
            $res = M('address')->add($data);
            if($res){
                $this->redirect('sureOrder');
            }else{
                $this->error('添加失败,请刷新重试！','sureOrder');
            }
        }
    }
    
    //支付操作
    public function payDoing()
    {
        //如果session存在，传递用户信息
        $midiuser = session('midiuser');
        if (!empty($midiuser)) {
            $this->assign('midiuser',$midiuser);
        }else{
            $this->error('您尚未登录，请去登录',U('Home/Index/login'));
        }
        if(IS_POST){
            $data = I('post.');
            if(empty($data['order_details']) ||
            empty($data['order_address']) ||
            empty($data['pay_type'])){
                $this->error('请选择收货地址，或参数不全！',U('Home/GoodsCart/cart_list'));
            }
            // var_dump($data);
            if($data['order_id'] > 0){
                //待付款订单
                $this->hasOrderPay($data,$midiuser);
                return;
            }

            //验证数据有效性
            $order_goods_arr = explode(',',$data['order_details']);
            $check = true;
            $goods_id_arr = [];
            if(!empty($order_goods_arr)){
                foreach ($order_goods_arr as $key => $val) {
                    $val = explode(':',$val);
                    $val[0] = (int)$val[0];
                    $val[1] = (int)$val[1];
                    $goods_id_arr[] = $val[0];
                    if($val[0] > 0 && $val[1] > 0){
                        $order_goods_arr[$key] = $val;
                    }else{
                        $check = false;
                        break;
                    }
                }
                if($check){
                    //查找商品单价计算总价格
                    $goods_data = M('goods')
                        ->field('goods_id,goods_name,goods_price,goods_sell_out,goods_display')
                        ->where(['goods_id'=>['in',$goods_id_arr]])
                        ->select();
                    //组装支付时需要用到数据
                    $data['goods_id'] = $goods_data[0]['goods_id'];
                    //判断是否有商品已售罄或已被删除 并计算商品总价格
                    $is_has = true;
                    $data['order_totalprice'] = 0;
                    $data['order_details'] = '';
                    $data['goods_name'] = '';
//                    var_dump($order_goods_arr);
                    foreach ($goods_data as $vals) {
                        if($vals['goods_sell_out'] == 2 || $vals['goods_display'] != 1){
                            $is_has = false;
                            break;
                        }else{
                            foreach ($order_goods_arr as $k => $v) {
                                if($vals['goods_id'] == $v[0]){
                                    $data['order_totalprice'] += ($vals['goods_price']*$v[1]);
                                    $data['order_details'] .= implode(':',$v).',';
                                    $data['goods_name'] .= $vals['goods_name'].',';
                                    unset($order_goods_arr[$k]);
                                }
                            }
                        }
                    }
                    if(!$is_has){
                        $this->error('您手速太慢了，有商品已售罄！',U('GoodsCart/cart_list'));
                        return;
                    }
                    $data['order_details'] = trim($data['order_details'],',');
                }else{
                    $this->error('参数不全,请重新下单！',U('GoodsCart/cart_list'));
                }
            }else{
                $this->error('参数不全,请重新下单！',U('GoodsCart/cart_list'));
            }
            //验证该用户是否存在该收货地址
            $has_address = M('address')
                ->where([
                    'address_id'=>$data['order_address'],
                    'address_user_id'=>$midiuser['user_id']
                ])
                ->find();
            if(empty($has_address)){
                $this->error('参数有误,请重新下单！',U('GoodsCart/cart_list'));
            }
            if(!in_array($data['pay_type'],[1,2])){
                $this->error('参数有误,请重新下单！',U('GoodsCart/cart_list'));
            }
            //生成订单相关信息
            $data['order_num'] = createOrdernum();
            $data['order_user_id'] = $midiuser['user_id'];
            $data['order_createtime'] = time();
            $data['order_name'] = trim($data['goods_name'],',');
//            var_dump($data);die;
//            var_dump($goods_id_arr);
            //判断是立即支付还是购物车中
            
            // 1是立即支付 2从购物车中进行支付
            if($data['toType'] == 1){
                $add_order = M('order')->add($data);

                if($add_order){
                    //立即支付
                    if($data['pay_type'] == 1){
                        //支付宝
                        A('Api/AliPayWeb')->aliPayDong($data);
                    }else if($data['pay_type'] == 2){
                        //微信支付
                        $data['order_id'] = $add_order;
                        A('Api/WxShaoMa')->wxShaoMaDoing($data);
                    }
                }else{
                    $this->error('下单失败，请刷新重试！',U('GoodsCart/cart_list'));
                }
            }else if($data['toType'] == 2){
                // var_dump($data);die;
                //清除购物车中相应商品
                M()->startTrans();
                $add_order = M('order')->add($data);
                $clear_res = $this->clearShopingCart($midiuser,$goods_id_arr);
                if($add_order && $clear_res){
                    M()->commit();
                    if($data['pay_type'] == 1){
                        //支付宝
                        A('Api/AliPayWeb')->aliPayDong($data);
                    }else if($data['pay_type'] == 2){
                        //微信支付
                        $data['order_id'] = $add_order;
                        A('Api/WxShaoMa')->wxShaoMaDoing($data);
                    }
                }else{
                    $this->error('参数有误！',U('GoodsCart/cart_list'));
                }
            }
        }else{
            $this->error('迷路了吧！',U('Home/Tutorial/index'));
        }
    }

    //待支付订单的支付
    public function hasOrderPay($data,$midiuser)
    {
        //查询订单详情
        $orderInfo = M('order')
            ->field('order_id,order_name,order_address,order_num,order_details,order_totalprice')
            ->where(['order_user_id'=>$midiuser['user_id']])
            ->find($data['order_id']);
        if(!empty($orderInfo)){
            //判断是否更换收货地址或付款方式
            if($data['order_address'] != $orderInfo['order_address']){
                M('order')->save(['order_id'=>$orderInfo['order_id'],'order_address'=>$data['order_address']]);
            }
            //支付时需要的商品ID
            $idStr = setGoodsDetailData($orderInfo['order_details']);
            $orderInfo['goods_id'] = $idStr['goods_id_arr'][0];
            if($data['pay_type'] == 1){
                //支付宝
                A('Api/AliPayWeb')->aliPayDong($orderInfo);
            }else if($data['pay_type'] == 2){
                //微信支付
                A('Api/WxShaoMa')->wxShaoMaDoing($orderInfo);
            }else{
                $this->error('参数有误！',U('Home/Order/orderList'));
            }
        }else{
            $this->error('参数有误！',U('Home/Order/orderList'));
        }
    }
    
    //下单成功清除购物车中此商品
    public function clearShopingCart($midiuser,$id_arr)
    {
        $cart_model = M('shoppingcart');
        $info = $cart_model
            ->field('shoppingcart_totalprice',true)
            ->where(['shoppingcart_user_id'=>$midiuser['user_id']])
            ->find();
        if(!empty($info['shoppingcart_details'])) {
            $new_arr = explode(',', $info['shoppingcart_details']);
            if (count($id_arr) > 1) {
                foreach ($new_arr as $key => $val) {
                    foreach ($id_arr as $k => $v) {
                        if (trim(strstr($val, ':', true)) == $v) {
                            unset($id_arr[$k]);
                            unset($new_arr[$key]);
                        }
                    }
                }
            } else {
                foreach ($new_arr as $key => $val) {
                    if (trim(strstr($val, ':', true)) == $id_arr[0]) {
                        unset($new_arr[$key]);
                    }
                }
            }
            $info['shoppingcart_details'] = implode(',', $new_arr);
            $res = $cart_model->save($info);
            if($res){
                return true;
            }
        }
        return false;
    }

    //微信支付页面中ajax请求判断指定订单是否已支付
    public function isPay()
    {
        if(IS_AJAX){
            //如果session存在，传递用户信息
            $midiuser = session('midiuser');
            $order_id = I('id',0,'intval');
            if($order_id > 0){
                $status = M('order')
                    ->where([
                        'order_id'=>$order_id,
                        'order_user_id'=>$midiuser['user_id'],
                    ])
                    ->getField('order_paystatus');
                if($status == 2){
                    $this->ajaxReturn([
                        'status'=>1,
                        'msg'=>'支付成功！',
                        'data'=>U('Home/Order/orderList',array('status'=>2))
                    ]);
                }else if($status == 1){
                    $this->ajaxReturn([
                        'status'=>3,
                        'msg'=>'未支付！',
                        'data'=>''
                    ]);
                }
            }else{
                $this->ajaxReturn([
                    'status'=>2,
                    'msg'=>'参数有误！',
                    'data'=>U('Home/Tutorial/index')
                ]);
            }
        }
    }
    
    //订单列表页
    public function orderList()
    {
        //如果session存在，传递用户信息
        $midiuser = session('midiuser');
        if(empty($midiuser)){
            $this->error('请先登录！',U('Home/Index/login'));
        }
        $order_paystatus = I('status',1,'intval');
        if($order_paystatus > 0){
            $wh['order_paystatus'] = ['eq',$order_paystatus];
        }
        $wh['order_user_id'] = ['eq',$midiuser['user_id']];
        $json_arr = array_filter($_GET);
        $p = (!empty($json_arr['p']))?$json_arr['p']:1;
        $pnum = (!empty($json_arr['pnum']))?$json_arr['pnum']:2;
        $order_model = M('order');
        $count = $order_model
            ->where($wh)
            ->count();
        $page = getpage($count,$pnum);
        $data_list = $order_model
            ->field()
            ->where($wh)
            ->page($p,$pnum)
            ->order('order_createtime desc')
            ->select();
        if(!empty($data_list)){
            foreach ($data_list as &$val) {
                if($val['order_paystatus'] == 1){
                    $val['status'] = '待付款';
                }else if($val['order_paystatus'] == 2){
                    $val['status'] = '已付款,待发货';
                }else if($val['order_paystatus'] == 3){
                    $val['status'] = '已发货';
                }
                $val['order_createtime'] = date('Y-m-d H:i:s',$val['order_createtime']);
            }
        }
        $this->assign('status',$order_paystatus);
        $this->assign('page',$page->show());
        $this->assign('data_list',$data_list);
        $this->display();
    }
}